package com.eduagent.xwqeduagent.api.TextCorrection;

import com.alibaba.fastjson.JSON;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

/**
 * 文本纠错API演示程序
 * 独立运行的示例，不依赖Spring框架
 *
 * 使用方法：
 * 1. 将下方的APP_ID, API_KEY, API_SECRET替换为您的讯飞账号对应的值
 * 2. 运行main方法
 * 3. 查看控制台输出的结果
 */
public class TextCorrectionDemo {

    // API配置信息
    private static final String API_URL = "https://api.xf-yun.com/v1/private/s9a87e3ec";
    private static final String HOST = "api.xf-yun.com";
    private static final String REQUEST_LINE = "POST /v1/private/s9a87e3ec HTTP/1.1";

    // 请在此处填写您的讯飞文本纠错API配置
    // 可以使用与其他讯飞服务相同的密钥，或配置单独的密钥
    private static final String APP_ID = "637d1630";
    private static final String API_KEY = "8bd0514cb66802c719bbf34a908a0119";
    private static final String API_SECRET = "NzUyY2Y3OTYwYjAyMGExODc5OTM1ZGZl";
    
    /**
     * 演示程序入口
     */
    public static void main(String[] args) {
        try {
            // 设置测试文本
            String text = "大月当头照，小鸟叫早了，画蛇天足多此一举。";
            
            // 创建HTTP客户端
            HttpClient httpClient = HttpClient.newBuilder()
                    .version(HttpClient.Version.HTTP_1_1)
                    .build();
            
            // 生成鉴权参数
            String date = getGMTDate();
            String authUrl = getAuthUrl(date);
            
            // 构建请求体
            String requestBody = buildRequestBody(text);
            
            System.out.println("请求URL: " + authUrl);
            System.out.println("请求体: " + requestBody);
            
            // 发送HTTP请求
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(authUrl))
                    .header("Content-Type", "application/json")
                    .header("Date", date)
                    .POST(HttpRequest.BodyPublishers.ofString(requestBody))
                    .build();
            
            // 发送请求并获取响应
            HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
            
            // 检查响应状态码
            int statusCode = response.statusCode();
            System.out.println("响应状态码: " + statusCode);
            
            if (statusCode == 200) {
                // 处理响应结果
                String responseBody = response.body();
                System.out.println("原始响应: " + responseBody);
                
                // 解析响应结果
                String resultText = parseResponseText(responseBody);
                System.out.println("Base64解码后的结果: " + resultText);
                
                // 将结果解析为对象
                TextCorrectionResult result = JSON.parseObject(resultText, TextCorrectionResult.class);
                
                // 输出纠错结果
                System.out.println("\n纠错结果详情:");
                if (result.getCharacter() != null && !result.getCharacter().isEmpty()) {
                    System.out.println("  别字纠错: " + result.getCharacter());
                }
                
                if (result.getWord() != null && !result.getWord().isEmpty()) {
                    System.out.println("  别词纠错: " + result.getWord());
                }
                
                if (result.getIdm() != null && !result.getIdm().isEmpty()) {
                    System.out.println("  成语纠错: " + result.getIdm());
                }
                
                if (result.getPunc() != null && !result.getPunc().isEmpty()) {
                    System.out.println("  标点纠错: " + result.getPunc());
                }
            } else {
                System.out.println("请求失败，响应体: " + response.body());
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 构建请求体
     */
    private static String buildRequestBody(String text) {
        StringBuilder json = new StringBuilder();
        json.append("{\n");
        
        // header部分
        json.append("  \"header\": {\n");
        json.append("    \"app_id\": \"").append(APP_ID).append("\",\n");
        json.append("    \"status\": 3\n");
        json.append("  },\n");
        
        // parameter部分
        json.append("  \"parameter\": {\n");
        json.append("    \"s9a87e3ec\": {\n");
        json.append("      \"result\": {\n");
        json.append("        \"encoding\": \"utf8\",\n");
        json.append("        \"compress\": \"raw\",\n");
        json.append("        \"format\": \"json\"\n");
        json.append("      }\n");
        json.append("    }\n");
        json.append("  },\n");
        
        // payload部分
        json.append("  \"payload\": {\n");
        json.append("    \"input\": {\n");
        json.append("      \"encoding\": \"utf8\",\n");
        json.append("      \"compress\": \"raw\",\n");
        json.append("      \"format\": \"json\",\n");
        json.append("      \"status\": 3,\n");
        json.append("      \"text\": \"").append(Base64.encodeBase64String(text.getBytes(StandardCharsets.UTF_8))).append("\"\n");
        json.append("    }\n");
        json.append("  }\n");
        json.append("}");
        
        return json.toString();
    }
    
    /**
     * 从响应中解析结果文本
     */
    private static String parseResponseText(String responseBody) {
        try {
            com.alibaba.fastjson.JSONObject responseJson = JSON.parseObject(responseBody);
            
            // 获取结果文本
            com.alibaba.fastjson.JSONObject payload = responseJson.getJSONObject("payload");
            com.alibaba.fastjson.JSONObject result = payload.getJSONObject("result");
            String resultText = result.getString("text");
            
            // Base64解码结果
            return new String(Base64.decodeBase64(resultText), StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
            return "解析失败: " + e.getMessage();
        }
    }
    
    /**
     * 获取GMT格式的日期字符串
     */
    private static String getGMTDate() {
        SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        format.setTimeZone(TimeZone.getTimeZone("GMT"));
        return format.format(new Date());
    }
    
    /**
     * 生成鉴权URL
     */
    private static String getAuthUrl(String date) {
        try {
            // 构建鉴权原始字符串
            String signatureOrigin = "host: " + HOST + "\n" +
                    "date: " + date + "\n" +
                    REQUEST_LINE;
            
            // 使用HMAC-SHA256算法生成签名
            Mac hmacSha256 = Mac.getInstance("HmacSHA256");
            hmacSha256.init(new SecretKeySpec(API_SECRET.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
            byte[] signatureSha = hmacSha256.doFinal(signatureOrigin.getBytes(StandardCharsets.UTF_8));
            String signature = Base64.encodeBase64String(signatureSha);
            
            // 构建authorization参数原始字符串
            String authorizationOrigin = "api_key=\"" + API_KEY + "\", algorithm=\"hmac-sha256\", headers=\"host date request-line\", signature=\"" + signature + "\"";
            
            // Base64编码
            String authorization = Base64.encodeBase64String(authorizationOrigin.getBytes(StandardCharsets.UTF_8));
            
            // URL编码date参数
            String encodedDate = URLEncoder.encode(date, StandardCharsets.UTF_8.toString());
            
            // 拼接最终URL
            return API_URL + "?authorization=" + authorization +
                    "&host=" + HOST +
                    "&date=" + encodedDate;
            
        } catch (Exception e) {
            e.printStackTrace();
            return "生成鉴权URL失败: " + e.getMessage();
        }
    }
} 